from django.db import models
from django.db.models import Q

class Player(models.Model):
    ''' Represents a player and their basic information
    '''
    firstname = models.CharField(max_length=100)
    lastname  = models.CharField(max_length=100)
    number    = models.IntegerField()
    birthday  = models.DateField()
    height    = models.DecimalField(max_digits=5, decimal_places=2)
    weight    = models.DecimalField(max_digits=5, decimal_places=2)
    active    = models.BooleanField(default=True)
    comments  = models.TextField(null=True, blank=True)

    class Meta:
        ordering = ('lastname','firstname',)

    def __unicode__(self):
        return "%s, %s" % (self.lastname, self.firstname)

    @classmethod
    def byName(cls, name):
        ''' A helper method to search for a player by name

        :param name: The name to search with
        :returns: Any matching players
        '''
        return Player.objects.get(Q(firstname__istartswith=name)
            | Q(lastname__istartswith=name))

class Reading(models.Model):
    ''' Represents a single reading for a given player

    .. note:: The temperature and humidity will be the max value
              for the given session. Also, except for notable hits,
              the acceleration will be the aggregate for the session.
    '''
    player       = models.ForeignKey('Player', related_name='readings')
    date         = models.DateTimeField(auto_now=True)
    hits         = models.IntegerField(default=0)
    temperature  = models.DecimalField(max_digits=6, decimal_places=2)
    humidity     = models.DecimalField(max_digits=6, decimal_places=2)
    acceleration = models.DecimalField(max_digits=8, decimal_places=3)

    class Meta:
        ordering = ('date',)

    def __unicode__(self):
        return "%s:[%fh][%ff][%fg]" % (self.date, self.humidity, self.temperature, self.acceleration)

